﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using MySql.Data.MySqlClient;
using System.Data.OleDb;
using System.Configuration;

namespace SHRMS
{
    /// <summary>
    /// 数据库类型
    /// </summary>
    public enum DbType
    {
        SqlServer, MySql, Sqlite, OleDb
    }
    public class DbFactory
    {
        public readonly IDbConnection DefaultDbConnection;

        public DbFactory()
        {
            string DefaultDb = ConfigurationManager.AppSettings["DefaultDb"];
            var _dbType =(DbType) Enum.Parse(typeof(DbType), DefaultDb, true);
            string ConnectionString = ConfigurationManager.AppSettings[DefaultDb];
            DefaultDbConnection = DbConnectionObject(_dbType, ConnectionString);
        }

        public DbFactory(DbType dbType,string ConnectionString)
        {
            DefaultDbConnection = DbConnectionObject(dbType, ConnectionString);
        }

        /// <summary>
        /// 获取数据库连接对象
        /// </summary>
        /// <param name="dbType">数据库类型</param>
        /// <param name="ConnectionString">数据库连接字符串</param>
        /// <returns></returns>
        public IDbConnection DbConnectionObject(DbType dbType,string ConnectionString)
        {
            IDbConnection _dbConnection = null;
            switch (dbType)
            {
                case DbType.SqlServer:
                    _dbConnection = SqlServerDb(ConnectionString);
                    break;
                case DbType.MySql:
                    _dbConnection = MySqlDb(ConnectionString);
                    break;
                case DbType.Sqlite:
                    _dbConnection = SqliteDb(ConnectionString);
                    break;
                case DbType.OleDb:
                    _dbConnection = OleDb(ConnectionString);
                    break;
                default:
                    break;
            }
            return _dbConnection;
        }

        public IDbConnection SqlServerDb(string SqlConnectionString)
        {
            return new SqlConnection(SqlConnectionString);
        }
        public IDbConnection MySqlDb(string MySqlConnectionString)
        {
            return new MySqlConnection(MySqlConnectionString);
        }
        public IDbConnection SqliteDb(string SqliteConnectionString)
        {
            return new SQLiteConnection(SqliteConnectionString);
        }
        public IDbConnection OleDb(string OleDbConnectionString)
        {
            return new OleDbConnection(OleDbConnectionString);
        }
    }
}
